package com.xxx.store.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxx.store.entity.UserSelect;
import com.xxx.store.entity.Vote;
import com.xxx.store.entity.VoteItem;
import com.xxx.store.mapper.UserMapper;
import com.xxx.store.service.TypeService;
import com.xxx.store.service.UserSelectService;
import com.xxx.store.service.VoteItemService;
import com.xxx.store.service.VoteService;
import com.xxx.store.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-04-26
 */
@RestController
@RequestMapping("/vote")
public class VoteController extends BaseController<Vote, VoteService> {

    @Autowired
    VoteService voteService;

    @Autowired
    VoteItemService voteItemService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserSelectService userSelectService;

    @Autowired
    TypeService typeService;

    @Override
    public Result add(@RequestBody Vote vote) {
        voteService.save(vote);
        for (VoteItem voteItem : vote.getItemList()) {
            voteItem.setVoteId(vote.getId());
            voteItemService.save(voteItem);
        }
        return Result.ok("添加成功", vote);
    }

    @Override
    public Result list() {
        List<Vote> list = voteService.list(new QueryWrapper<Vote>().orderByDesc("create_time"));
        for (Vote vote : list) {
            fillVote(vote);
        }
        return Result.ok(list);
    }

    private void fillVote(Vote vote) {
        QueryWrapper<VoteItem> qw = new QueryWrapper<>();
        qw.eq("vote_id", vote.getId());
        List<VoteItem> itemList = voteItemService.list(qw);
        itemList.sort((o1, o2) -> o1.getNo() - o2.getNo());
        vote.setItemList(itemList);
        vote.setUser(userMapper.getByIdIgnore(vote.getUserId()));
        vote.setType(typeService.getById(vote.getTypeId()));
    }

    // 获取一个用户投过票的列表
    @GetMapping("/getJoinByUserId")
    public Result getJoinByUserId(Integer userId) {
        List<UserSelect> userSelectList = userSelectService.list(new QueryWrapper<UserSelect>().eq("user_id", userId));
        List<Vote> result = new ArrayList<>();
        for (UserSelect userSelect : userSelectList) {
            Vote vote = voteService.getById(userSelect.getVoteId());
            if (vote != null) {
                fillVote(vote);
                result.add(vote);
            }
        }
        return Result.ok(result);
    }
}

